<template>
  <view v-if="nextTicket" class="page-box TrainItem lg">
    <view class="px-base py-llg">
      <view>
        <u-row :gutter="12">
          <u-col :span="4">
            <view class="Time">{{
              nextTicket.fromTime | timeFormat("HH:mm")
            }}</view>
            <view class="Station">{{ nextTicket.from }}</view>
          </u-col>
          <u-col :span="4">
            <view class="text-center">
              <view class="my-ssm">{{ nextTicket.trainNo }}</view>
              <u-line></u-line>
              <view
                class="my-ssm text-center text-info"
                :style="{ fontSize: '15px' }"
                >{{ $u.dayjs(nextTicket.date).format("MM月DD日") }}&ensp;{{
                  $u.dayjs(nextTicket.date).isToday()
                    ? "今天"
                    : $u.timeFormat(nextTicket.date, "[周]dd")
                }}</view
              >
            </view>
          </u-col>
          <u-col :span="4">
            <view class="Time text-end">{{
              nextTicket.toTime | timeFormat("HH:mm")
            }}</view>
            <view class="Station text-end">{{ nextTicket.to }}</view>
          </u-col>
        </u-row>
      </view>
    </view>
  </view>
  <view v-else-if="loading" class="u-flex-xy-center p-base">
    <text class="text-info">加载中...</text>
  </view>
  <view v-else class="u-flex-xy-center p-base">
    <text class="text-info">当前没有出行计划</text>
  </view>
</template>

<script>
import { mapState } from "vuex";
import apiTickets from "@/api/tickets";
import { timeAscCompareFn } from "@/utils/functions.js";

export default {
  data() {
    return {
      loading: false,
      nextTicket: undefined,
    };
  },
  computed: {
    ...mapState({ auth: "auth" }),
  },
  mounted() {
    this.loadMyTickets();
  },
  methods: {
    loadMyTickets() {
      this.loading = true;
      apiTickets
        .get()
        .then((res) => {
          this.nextTicket = res.data
            .sort(
              (a, b) =>
                timeAscCompareFn(a.fromTime, b.fromTime) ||
                timeAscCompareFn(a.toTime, b.toTime) ||
                a.id - b.id
            )
            .find((tkt) => uni.$u.dayjs().isBefore(uni.$u.dayjs(tkt.toTime)));
        })
        .catch(() => {
          this.nextTicket = undefined;
        })
        .then(() => {
          this.loading = false;
        });
    },
  },
};
</script>
